﻿using BabyPoetryConference.Base;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BabyPoetryConference.WinUI
{
    public class Startup : ApplicationContext
    {
        private static readonly Logger _Logger = LogManager.GetCurrentClassLogger();
        private readonly MainForm _workbench;
        private readonly IServiceManager _manager;

        public Startup(MainForm workbench, IServiceManager manager)
        {
            _workbench = workbench;
            _manager = manager;
            Application.ApplicationExit += OnApplicationExit;
            LoadEnvironment();
        }

        private void LoadEnvironment()
        {
            _Logger.Info($"=============================================================================");
            _Logger.Info($">>>>>> {DateTime.Now.ToLongDateString()} {DateTime.Now.ToShortTimeString()}<<<<<<");
            _Logger.Info($">>>>>> {AppDomain.CurrentDomain.BaseDirectory} <<<<<<");

            _Logger.Info("开始加载...");

            _manager.LoadCoreService();

            if (_workbench is Form mainWorkbench)
            {
                mainWorkbench.Shown += (s, e) =>
                {
                    mainWorkbench.Activate();
                    _Logger.Info("主控台载入完成.");
                };
                mainWorkbench.Closed += (s, e) =>
                {
                    _Logger.Info("软件准备关闭...");
                    Application.Exit();
                };
                mainWorkbench.Show();
                mainWorkbench.Refresh();
            }
        }

        /// <summary>
        ///     应用程序退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnApplicationExit(object sender, EventArgs e)
        {
            try
            {
                _manager.UnloadCoreService();
            }
            catch (Exception exception)
            {
                _Logger.Error(exception, "卸载核心服务及插件");
            }
        }
    }
}
